<?php
/**
 * Created by PhpStorm.
 * Author: kaodou
 * Date: 2017/10/18
 * Time: 14:33
 */
namespace App\Http\Admin\Category\Models;

use Framework\BaseClass\Http\Admin\Model;
use App\Eloquent\Admin\Category as EloquentCategory;

class Category extends Model
{
//    protected $fillable = ['pid', 'cat_name'];
    protected $dates = ['deleted_at'];

    public function getCategoryList()
    {
        return EloquentCategory::all();
    }

    public function getChildrenList($pid = 0)
    {
        return EloquentCategory::where('pid', $pid)->get();
    }

    /**
     * @param int $pid
     * @param array $result
     * @return array 返回一维数组
     */
    public function getCategoryOption($pid = 0,$result = [],$level = 0)
    {
        $level++;
        $list = EloquentCategory::where('pid', $pid)->get();
        $list = $list->toArray();
//        dd($list);
        foreach ($list as $k => $v) {
            $v['level'] = $level;
            $result[] = $v;
            $result = self::getCategoryOption($v['id'],$result,$level);
        }
        return $result;
    }

    /**
     * @param int $pid
     * @param array $result
     * @return array 返回递归数组
     */
    public function getCategoryTree($pid = 0,$result = [])
    {
        $list = EloquentCategory::where('pid', $pid)->get();
        $list = $list->toArray();
//        dd($list);
        foreach ($list as $k => $v) {
            $child = self::getCategoryTree($v['id']);
            $v['child'] = $child;
            $result[] = $v;
        }
        return $result;
    }

    public function addCategory($cat_name, $display, $pid = '0')
    {
        $CategoryHandel = new EloquentCategory();
        $saveData = [
            'pid' => $pid,
            'cat_name' => $cat_name,
            'display' => $display
        ];

        return $this->saveCategory($CategoryHandel, $saveData);
    }

    public function updateCategory($id, $cat_name, $display, $pid = 0)
    {
        $CategoryHandel = EloquentCategory::find($id);
        if (!$CategoryHandel) xThrow(ERR_CLIENT_USER_NOT_EXIST);
        $saveData = [
            'pid' => $pid,
            'cat_name' => $cat_name,
            'display' => $display
        ];

        return $this->saveCategory($CategoryHandel, $saveData);
    }

    private function saveCategory(EloquentCategory $CategoryHandel, array $saveData)
    {
        $CategoryHandel->fill($saveData);
        return $CategoryHandel->save();
    }

    public function delCategory($CategoryId)
    {
        $CategoryHandel = EloquentCategory::find($CategoryId);
        if (!$CategoryHandel) xThrow(ERR_CLIENT_USER_NOT_EXIST);
        return $CategoryHandel->delete();
    }
}